import userApi from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { adaptLoginResponse, adaptUserInfoResponse } from '@/utils/adapter'

const state = {
    token: getToken(),
    userId: null,
    username: '',
    avatar: '',
    roles: [],
    permissions: [],
    userInfo: {}
}

const mutations = {
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_USER_ID: (state, userId) => {
        state.userId = userId
    },
    SET_USERNAME: (state, username) => {
        state.username = username
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
        state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
        state.permissions = permissions
    },
    SET_USER_INFO: (state, userInfo) => {
        state.userInfo = userInfo
    },
    RESET_USER: (state) => {
        state.token = ''
        state.userId = null
        state.username = ''
        state.avatar = ''
        state.roles = []
        state.permissions = []
        state.userInfo = {}
    }
}

const actions = {
    // 用户登录
    login({ commit }, userInfo) {
        const { username, password } = userInfo
        console.log('尝试登录:', { username, password: '***隐藏***' })
        return new Promise((resolve, reject) => {
            userApi.login({ username: username.trim(), password: password })
                .then(response => {
                    console.log('登录响应:', response)

                    try {
                        // 使用适配器处理响应
                        const adaptedResponse = adaptLoginResponse(response)
                        const token = adaptedResponse.token

                        console.log('获取到token:', token)

                        // 确保token存在且不为空
                        if (!token) {
                            const error = new Error('登录失败，未获取到有效token')
                            console.error(error.message)
                            reject(error)
                            return
                        }

                        // 保存token并更新状态
                        const tokenSaved = setToken(token)
                        if (!tokenSaved) {
                            console.warn('Token保存可能存在问题，尝试再次保存')
                            // 再次尝试保存
                            setTimeout(() => setToken(token), 100)
                        }

                        commit('SET_TOKEN', token)
                        resolve()
                    } catch (error) {
                        console.error('处理登录响应时出错:', error)
                        reject(error)
                    }
                })
                .catch(error => {
                    console.error('登录请求失败:', error)
                    reject(error)
                })
        })
    },

    // 获取用户信息
    getInfo({ commit, state }) {
        console.log('尝试获取用户信息, 当前token:', state.token)
        return new Promise((resolve, reject) => {
            userApi.getCurrentUserDetail()
                .then(response => {
                    console.log('获取用户信息响应:', response)

                    // 使用适配器处理响应
                    const adaptedData = adaptUserInfoResponse(response)

                    if (!adaptedData) {
                        console.error('验证失败: 未获取到用户数据')
                        reject('验证失败，请重新登录')
                        return
                    }

                    const { userId, username, avatar, roles, permissions } = adaptedData
                    console.log('适配后的用户信息:', { userId, username, roles, permissions })

                    // 角色和权限验证
                    if (!roles || roles.length <= 0) {
                        console.error('验证失败: 用户角色为空')
                        reject('用户角色必须是非空数组!')
                        return
                    }

                    commit('SET_USER_ID', userId)
                    commit('SET_USERNAME', username)
                    commit('SET_AVATAR', avatar)
                    commit('SET_ROLES', roles)
                    commit('SET_PERMISSIONS', permissions)
                    commit('SET_USER_INFO', adaptedData)
                    resolve(adaptedData)
                })
                .catch(error => {
                    console.error('获取用户信息失败:', error)
                    reject(error)
                })
        })
    },

    // 退出登录
    logout({ commit, state, dispatch }) {
        return new Promise((resolve, reject) => {
            userApi.logout()
                .then(() => {
                    commit('RESET_USER')
                    removeToken()
                    // 重置已访问视图和缓存视图
                    dispatch('tagsView/delAllViews', null, { root: true })
                    resolve()
                })
                .catch(error => {
                    reject(error)
                })
        })
    },

    // 前端登出
    fedLogOut({ commit }) {
        return new Promise(resolve => {
            commit('RESET_USER')
            removeToken()
            resolve()
        })
    },

    // 重置令牌
    resetToken({ commit }) {
        return new Promise(resolve => {
            commit('RESET_USER')
            removeToken()
            resolve()
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
} 